package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户资源控制器
 */
@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    ITravelService travelService;

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping
    public JSONResult register(User user){
        JSONResult result = new JSONResult();
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public JSONResult update(User user){
        userService.update(user);
        //把user又传到页面中
        return  new JSONResult().setResult(user);
    }

    /**
     * 根据用户id查询游记列表
     * @param qo
     * @return
     */
    @GetMapping("/{authorId}/travels")
    public PageInfo listTravels(TravelQuery qo){
        //按照最后更新时间倒序
        qo.setOrderBy("t.lastUpdateTime desc");
        return travelService.query(qo);
    }

    /**
     * 通过用户id,查询出他的数据
     * @param userId
     * @return
     */
    @GetMapping
    public User get(Long userId){
        return userService.getUser(userId);
    }

}
